from flask import Flask, request, render_template_string, redirect
import plotly.graph_objects as go
import traceback
from collections import Counter
import webbrowser
import threading
import time
import os

app = Flask(__name__)

# 首页模板
INDEX_TEMPLATE = """
<!DOCTYPE html>
<html dir="rtl" lang="ug">
<head>
    <meta charset="UTF-8">
    <title>ئۇيغۇر تىلى سۆز چاستوتا ئانالىز سىستېمىسى</title>
    <style>
        body {
            font-family: 'Microsoft Uighur', sans-serif;
            margin: 0;
            padding: 24px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 32px;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        .title {
            text-align: center;
            color: #2c3e50;
            font-size: 32px;
            margin-bottom: 32px;
        }
        textarea {
            width: 100%;
            height: 300px;
            padding: 15px;
            margin: 20px 0;
            border: 2px solid #e0e6ed;
            border-radius: 10px;
            font-family: 'Microsoft Uighur';
            font-size: 16px;
            resize: vertical;
        }
        .button {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-family: 'Microsoft Uighur';
            font-size: 18px;
            display: block;
            margin: 20px auto;
            transition: all 0.3s ease;
        }
        .button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(52,152,219,0.4);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">ئۇيغۇر تىلى سۆز چاستوتا ئانالىز سىستېمىسى</h1>
        <form method="post" action="/analyze" id="analyzeForm">
            <textarea name="text" id="inputText" placeholder="بۇ يەرگە تېكىست كىرگۈزۈڭ..."></textarea>
            <button type="submit" class="button">ئانالىز قىلىش</button>
        </form>
    </div>
    
    <script>
        document.getElementById('analyzeForm').onsubmit = function(e) {
            const text = document.getElementById('inputText').value.trim();
            if (!text) {
                e.preventDefault();
                alert('تېكىست كىرگۈزۈڭ!');
                return false;
            }
            return true;
        }
    </script>
</body>
</html>
"""

@app.route('/')
def home():
    return render_template_string(INDEX_TEMPLATE)

def analyze_word_frequency(text):
    """分析词频"""
    try:
        # 定义维吾尔语标点符号
        punctuation_marks = ['،', '؟', '؛', '٭', '«', '»', '(', ')', ':', '"', '"', '„', '!', '.', '-', '—', '…', '،', '؟', '؛', '٭']
        
        # 清理文本：移除标点符号
        for mark in punctuation_marks:
            text = text.replace(mark, ' ')
        
        # 分词并过滤空字符串
        words = [word for word in text.split() if word.strip()]
        
        # 统计词频
        word_counts = Counter(words)
        
        # 获取前50个最常见的词
        return dict(word_counts.most_common(50))
    except Exception as e:
        print(f"词频分析错误: {str(e)}")
        raise

@app.route('/analyze', methods=['POST'])
def analyze():
    try:
        text = request.form.get('text', '').strip()
        if not text:
            return redirect('/')
        
        # 分析文本
        word_freq = analyze_word_frequency(text)
        
        # 准备数据
        words = list(word_freq.keys())
        freqs = list(word_freq.values())
        
        # 生成图表HTML
        plot_html = create_plot(words, freqs)
        
        # 返回结果页面
        return f"""
        <!DOCTYPE html>
        <html dir="rtl" lang="ug">
        <head>
            <meta charset="UTF-8">
            <title>ئانالىز نەتىجىسى</title>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
            <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
            <style>
                * {{
                    font-family: 'Microsoft Uighur', sans-serif !important;
                }}
                body {{
                    margin: 0;
                    padding: 24px;
                    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                }}
                .container {{
                    max-width: 1200px;
                    margin: 0 auto;
                    background: white;
                    padding: 32px;
                    border-radius: 16px;
                    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
                }}
                .title {{
                    text-align: center;
                    color: #2c3e50;
                    font-size: 28px;
                    margin-bottom: 32px;
                }}
                .export-buttons {{
                    display: flex;
                    justify-content: center;
                    gap: 15px;
                    margin: 20px 0;
                }}
                .button {{
                    background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
                    color: white;
                    padding: 10px 20px;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 16px;
                    transition: all 0.3s ease;
                }}
                .button:hover {{
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(46,204,113,0.4);
                }}
                .filter-section {{
                    background: #f8f9fa;
                    padding: 20px;
                    border-radius: 8px;
                    margin: 20px 0;
                }}
                .word-list {{
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                    gap: 10px;
                    margin: 15px 0;
                    max-height: 300px;
                    overflow-y: auto;
                    padding: 10px;
                }}
                .word-item {{
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    padding: 8px;
                    background: white;
                    border-radius: 4px;
                    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                }}
                .filter-buttons {{
                    display: flex;
                    justify-content: center;
                    gap: 10px;
                    margin-bottom: 15px;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1 class="title">سۆز چاستوتا ئانالىزى نەتىجىسى</h1>
                
                <div class="filter-section">
                    <h3>سۆزلەرنى تاللاش</h3>
                    <div class="filter-buttons">
                        <button onclick="selectAll()" class="button">ھەممىنى تاللاش</button>
                        <button onclick="deselectAll()" class="button">ھەممىنى تاللىماسلىق</button>
                        <button onclick="updateChart()" class="button">يېڭىلاش</button>
                    </div>
                    <div class="word-list">
                        {''.join(f'<div class="word-item"><input type="checkbox" id="word_{i}" value="{word}" checked><label for="word_{i}">{word} ({freq})</label></div>' for i, (word, freq) in enumerate(zip(words, freqs)))}
                    </div>
                </div>
                
                <div id="plotDiv">
                    {plot_html}
                </div>
                
                <div class="stats">
                    <p>جەمئىي سۆز سانى: <span id="totalWords">{len(words)}</span></p>
                    <p>ئوخشىمىغان سۆز سانى: <span id="uniqueWords">{len(set(words))}</span></p>
                </div>
                
                <div class="export-buttons">
                    <button onclick="exportImage()" class="button">رەسىم ساقلاش</button>
                    <button onclick="exportExcel()" class="button">Excel ساقلاش</button>
                </div>
                
                <div class="button-container">
                    <a href="/" class="button">يېڭى ئانالىز</a>
                </div>
            </div>

            <script>
                // 词语筛选功能
                function selectAll() {{
                    document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = true);
                }}
                
                function deselectAll() {{
                    document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
                }}
                
                function updateChart() {{
                    const checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');
                    const selectedWords = [];
                    const selectedFreqs = [];
                    
                    checkedBoxes.forEach(cb => {{
                        const word = cb.value;
                        const index = {str(words)}.indexOf(word);
                        if (index !== -1) {{
                            selectedWords.push(word);
                            selectedFreqs.push({str(freqs)}[index]);
                        }}
                    }});
                    
                    // 更新图表
                    const trace = {{
                        x: selectedFreqs.slice().reverse(),
                        y: selectedWords.slice().reverse(),
                        type: 'bar',
                        orientation: 'h',
                        marker: {{
                            color: selectedFreqs.slice().reverse(),
                            colorscale: 'Viridis',
                            showscale: true
                        }}
                    }};
                    
                    const layout = {{
                        title: {{
                            text: 'سۆز تەكرارلىنىش ئانالىزى',
                            font: {{family: 'Microsoft Uighur', size: 24}}
                        }},
                        font: {{family: 'Microsoft Uighur', size: 14}},
                        height: 800,
                        margin: {{l: 150, r: 50, t: 100, b: 50}}
                    }};
                    
                    Plotly.newPlot('plotDiv', [trace], layout);
                    
                    // 更新统计信息
                    document.getElementById('totalWords').textContent = selectedWords.length;
                    document.getElementById('uniqueWords').textContent = new Set(selectedWords).size;
                }}
                
                async function exportImage() {{
                    try {{
                        const element = document.querySelector('.container');
                        const canvas = await html2canvas(element, {{
                            scale: 2,
                            useCORS: true,
                            backgroundColor: '#ffffff',
                            fontFamily: 'Microsoft Uighur',
                            onclone: function(clonedDoc) {{
                                Array.from(clonedDoc.getElementsByTagName('*')).forEach(el => {{
                                    el.style.fontFamily = 'Microsoft Uighur';
                                }});
                            }}
                        }});

                        const link = document.createElement('a');
                        link.download = 'سۆز_چاستوتا_ئانالىزى.png';
                        link.href = canvas.toDataURL('image/png');
                        link.click();
                    }} catch (error) {{
                        console.error('Error exporting image:', error);
                        alert('رەسىم ساقلاشتا خاتالىق كۆرۈلدى');
                    }}
                }}

                function exportExcel() {{
                    try {{
                        const data = [['سۆز', 'تەكرارلىنىش سانى']];
                        {str([[word, freq] for word, freq in zip(words, freqs)])}.forEach(item => {{
                            data.push(item);
                        }});
                        
                        const ws = XLSX.utils.aoa_to_sheet(data);
                        const wb = XLSX.utils.book_new();
                        XLSX.utils.book_append_sheet(wb, ws, 'سۆز چاستوتا ئانالىزى');
                        XLSX.writeFile(wb, 'سۆز_چاستوتا_ئانالىزى.xlsx');
                    }} catch (error) {{
                        console.error('Error exporting Excel:', error);
                        alert('Excel ساقلاشتا خاتالىق كۆرۈلدى');
                    }}
                }}
            </script>
        </body>
        </html>
        """
    except Exception as e:
        print(traceback.format_exc())
        return f"خاتالىق كۆرۈلدى: {str(e)}"

def open_browser():
    """在新线程中打开浏览器"""
    time.sleep(1.5)  # 等待Flask服务器启动
    webbrowser.open('http://127.0.0.1:5000/')

def create_plot(words, freqs):
    """创建图表"""
    fig = go.Figure()
    
    # 添加条形图
    fig.add_trace(go.Bar(
        x=freqs[::-1],
        y=words[::-1],
        orientation='h',
        marker=dict(
            color=freqs[::-1],
            colorscale='Viridis',
            showscale=True,
            colorbar=dict(
                title="تەكرارلىنىش سانى",
                titleside="right",
                titlefont=dict(size=14, family="Microsoft Uighur")
            )
        ),
        text=freqs[::-1],
        textposition='outside',
        textfont=dict(family='Microsoft Uighur', size=14)
    ))
    
    # 更新布局
    fig.update_layout(
        title=dict(
            text='سۆز تەكرارلىنىش ئانالىزى',
            font=dict(family='Microsoft Uighur', size=24),
            x=0.5
        ),
        font=dict(family='Microsoft Uighur', size=14),
        height=800,
        plot_bgcolor='rgba(245,247,250,0.95)',
        paper_bgcolor='rgba(245,247,250,0.95)',
        margin=dict(l=150, r=100, t=100, b=50),
        xaxis=dict(
            title='تەكرارلىنىش سانى',
            gridcolor='rgba(0,0,0,0.1)',
            showline=True,
            linecolor='rgba(0,0,0,0.2)',
            tickfont=dict(size=12)
        ),
        yaxis=dict(
            title='سۆزلەر',
            gridcolor='rgba(0,0,0,0.1)',
            showline=True,
            linecolor='rgba(0,0,0,0.2)',
            tickfont=dict(size=14)
        )
    )
    
    return fig.to_html(full_html=False, include_plotlyjs='https://cdn.plot.ly/plotly-latest.min.js')

if __name__ == "__main__":
    try:
        # 在新线程中启动浏览器
        threading.Thread(target=open_browser).start()
        
        # 启动Flask应用
        print("正在启动服务器...")
        app.run(port=5000, debug=False, threaded=True)
    except Exception as e:
        print(f"启动错误: {str(e)}")
        print(traceback.format_exc())
